package org.jgs1904.chanmufeng;

/**
 * 简单的懒汉式单例
 * 线程1执行的时候，线程2判断为null也执行，并返回不同的实例（obj1和obj2）：
 *
 * @author: 默苍璃
 * @date: 2024-07-01 10:02
 */
public class LazySimpleSingleton2 {

    private static LazySimpleSingleton2 instance;

    private LazySimpleSingleton2() {
    }

    public static LazySimpleSingleton2 getInstance() {

        if (instance == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            instance = new LazySimpleSingleton2();
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {

            LazySimpleSingleton2 singleton = LazySimpleSingleton2.getInstance();
            System.out.println("Thread 1: " + System.identityHashCode(singleton));
        });

        Thread thread2 = new Thread(() -> {
            LazySimpleSingleton2 singleton = LazySimpleSingleton2.getInstance();
            System.out.println("Thread 2: " + System.identityHashCode(singleton));
        });

        thread1.start();
        thread2.start();

    }

}
